package com.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.mapper.UserAddressMapper;
import com.shop.pojo.UserAddress;
import com.shop.service.UserAddressService;
import com.shop.vo.UserAddressQueryRequest;
import com.shop.vo.UserAddressSaveRequest;
import com.shop.vo.UserAddressUpdateRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service("userAddressService")
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {

    @Override
    public IPage<UserAddress> page(Page page, UserAddressQueryRequest request){
        QueryWrapper<UserAddress> wrapper = UserAddress.queryWrapper(request);
        return this.page(page,wrapper);
    }

    @Transactional
    @Override
    public void save(UserAddressSaveRequest request){
        UserAddress userAddress = new UserAddress();
        BeanUtils.copyProperties(request,userAddress);
        this.save(userAddress);
    }

    @Transactional
    @Override
    public void update(UserAddressUpdateRequest request){
        UserAddress userAddress = new UserAddress();
        BeanUtils.copyProperties(request,userAddress);
        userAddress.setId(request.getAddressId());
        this.updateById(userAddress);
    }

    @Transactional
    @Override
    public void delete(String id){
        this.removeById(id);
    }

    @Transactional
    @Override
    public void setDefalut(String userId, String addressId) {
        UpdateWrapper<UserAddress> update = new UpdateWrapper<>();
        update.eq(UserAddress.IS_DEFAULT,1);
        update.set(UserAddress.IS_DEFAULT,0);
        update.eq(UserAddress.USER_ID,userId);
        this.update(update);
        UpdateWrapper<UserAddress> updateDefault = new UpdateWrapper<>();
        updateDefault.set(UserAddress.IS_DEFAULT,1);
        updateDefault.eq(UserAddress.ID,addressId);
        this.update(updateDefault);
    }
}